package com.zxl.always.on.display.ui.widget.clock.digital;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import com.zxl.always.on.display.ui.widget.clock.StandAloneClock;

/**
 * Created by Administrator on 2018/2/28.
 */

public abstract class BaseTimeViewHolder extends LinearLayout implements StandAloneClock {

    private boolean mIsRegister, mIsStandAloneMode;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshTime();
        }
    };

    public BaseTimeViewHolder(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        refreshTime();
    }

    @Override
    public void pauseStandAloneMode() {
        setStandAloneMode(false);
    }

    @Override
    public void resumeStandAloneMode() {
        setStandAloneMode(mIsStandAloneMode);
        refreshTime();
    }

    @Override
    public void setStandAloneMode(boolean isStandAlone) {
        mIsStandAloneMode = isStandAlone;
        if (mIsStandAloneMode) {
            if (!mIsRegister) {
                try {
                    mIsRegister = true;
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(Intent.ACTION_TIME_TICK);
                    intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
                    intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
                    getContext().registerReceiver(mReceiver, intentFilter);
                } catch (Exception e) {
                    mIsRegister = false;
                }
            }
        } else {
            if (mIsRegister) {
                try {
                    getContext().unregisterReceiver(mReceiver);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void setBackgroundStyle(int position) {
    }
}
